import { Injectable } from "@nestjs/common"
import { EmailEntity } from "./email.entity"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import * as nodemailer from "nodemailer"
import { emailTemplate } from "../../templete/email"

@Injectable()
export class EmailService {
  constructor(
    @InjectRepository(EmailEntity)
    private readonly emailEntity: Repository<EmailEntity>
  ) {}
  /**
   * Obtain configuration parameters
   * @return configuration parameters
   */
  private get emailConfig() {
    return this.emailEntity.findOne({
      where: {
        id: 1
      }
    })
  }

  // /**
  //  * Send email
  //  * @param res
  //  * @param body
  //  */
  // public async send(res: any, body: any): Promise<void> {
  //   // 1.Obtain parameters
  //   const { to, subject, text } = body
  //   const { host, port, user, pass } = await this.emailConfig
  //   const mailOptions = {
  //     from: user,
  //     to,
  //     subject,
  //     text
  //   }
  //
  //   // 2.Establish a transmitter
  //   const transporter = nodemailer.createTransport({
  //     host, // SMTP server hostname: smtp.qq.com
  //     port, // SMTP server port: 587 or 465
  //     secure: true, // use SSL
  //     auth: {
  //       user, // SMTP server username
  //       pass // SMTP server password
  //     }
  //   })
  //
  //   // 3.Send email
  //   try {
  //     await transporter.sendMail(mailOptions)
  //     res.json({ status: "success", message: "邮件发送成功！" })
  //   } catch (err) {
  //     console.log(err)
  //     res.json({ status: "error", message: "邮件发送失败！" })
  //   } finally {
  //     // 4.Close the transmitter after sending the email
  //     transporter.close()
  //   }
  // }

  /**
   * Obtain the email configuration
   * @param res
   */
  public async getConfig(res: any) {
    try {
      const data = await this.emailEntity.findOne({ where: { id: 1 } })
      res.json(data)
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * Save the email configuration
   * @param res
   * @param body
   */
  public async saveConfig(res: any, body: any): Promise<void> {
    try {
      await this.emailEntity.save(body)
      res.json({ status: "success", message: "设置修改成功！" })
    } catch (err) {
      console.log(err)
      res.json({ status: "error", message: "服务器内部错误，请稍后再试！" })
    }
  }

  /**
   * Generate captcha
   * @param body
   * @param session
   */
  public async generateCaptcha(body: any, session: any): Promise<void> {
    const { to } = body
    const captchaValue = this.generateRandomCaptcha()
    const data = {
      to,
      subject: "[Author授权系统]收到验证码",
      text: emailTemplate(captchaValue)
    }
    session.emailCaptcha = captchaValue
    await this.sendEmail(data)
  }

  /**
   * Send email
   * @param data
   */
  private async sendEmail(data: any): Promise<void> {
    // 1.Obtain parameters
    const { to, subject, text } = data
    const { host, port, user, pass } = await this.emailConfig
    const mailOptions = {
      from: user,
      to,
      subject,
      text
    }

    // 2.Establish a transmitter
    const transporter = nodemailer.createTransport({
      host, // SMTP server hostname: smtp.qq.com
      port, // SMTP server port: 587 or 465
      secure: true, // use SSL
      auth: {
        user, // SMTP server username
        pass // SMTP server password
      }
    })

    // 3.Send email
    try {
      await transporter.sendMail(mailOptions)
    } catch (err) {
      console.log(err)
    } finally {
      // 4.Close the transmitter after sending the email
      transporter.close()
    }
  }

  /**
   * Generate random captcha
   * @private
   */
  private generateRandomCaptcha(): string {
    let result = ""
    const characters = "0123456789"
    const codeLength = 6

    for (let i = 0; i < codeLength; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length))
    }

    return result
  }
}
